import {
  formatTime
} from '../../../utils/util'
import Toast from 'tdesign-miniprogram/toast/index';

Page({
  page: {
    size: 5,
    num: 1,
  },
  /**
   * 页面的初始数据
   */
  data: {
    dialogKey: '',
    cntOrder: {
      order_status: '',
      order_no: ''
    },
    tabs: [{
        key: -1,
        text: '全部'
      },
      {
        key: 5,
        text: '待付款',
        info: ''
      },
      {
        key: 1,
        text: '待发货',
        info: ''
      },
      {
        key: 2,
        text: '待收货',
        info: ''
      },
      {
        key: 3,
        text: '已完成',
        info: ''
      },
    ],

    confirmBtn: {
      content: '确定',
      variant: 'base'
    },
    curTab: -1,
    cntList: [],
    orderList: [],
    showConfirm: false,
    listLoading: 0,
    pullDownRefreshing: false,
    emptyImg: 'https://cdn-we-retail.ym.tencent.com/miniapp/order/empty-order-list.png',
    backRefresh: false,
    status: -1,
  },
  onPullDownRefresh_(e) {
    const {
      callback
    } = e.detail;
    this.setData({
      pullDownRefreshing: true
    });
    this.refreshList(this.data.curTab)
      .then(() => {
        this.setData({
          pullDownRefreshing: false
        });
        callback && callback();
      })
      .catch((err) => {
        this.setData({
          pullDownRefreshing: false
        });
        Promise.reject(err);
      });
  },
  closeDialog() {
    // const {
    //   dialogKey
    // } = this.data;
    this.setData({
      showConfirm: false
    });
  },
  onReachBottom() {
    if (this.data.listLoading === 0) {
      this.getOrderList(this.data.curTab);
    }
  },
  onReTryLoad() {
    this.getOrderList(this.data.curTab);
  },
  confirmDialog() {
    this.setData({
      showConfirm: false
    });
    this.updateOrder()
  },
  updateOrder() {
    let order_no = this.data.cntOrder.order_no
    let order_status = this.data.cntOrder.order_status
    wx.cloud.callFunction({
      name: 'updateOrder',
      data: {
        flag: 'update',
        order_no: order_no,
        order_status
      }
    }).then(res => {
      Toast({
        context: this,
        selector: '#t-toast',
        message: `操作成功`,
        theme: 'success',
      });
    }).catch(err => {
      console.error(err)
    })
    let _this = this
    setTimeout(() => {
      _this.onRefresh()
    }, 500)
  },
  getOrderList() {
    let _this = this
    wx.cloud.callFunction({
      name: 'getOrders'
    }).then(res => {
      console.log('data==>', res)
      let list = res.result.data.list
      let status = _this.data.status
      // 根据状态筛选订单数据
      const cntList = list.filter(item => {
        if (status === -1) {
          return true; // 全部订单
        } else {
          return item.order_status === status; // 筛选指定状态的订单
        }
      });
      // 更新状态和订单列表
      _this.setData({
        orderList: res.result.data.list,
        cntList: cntList
      })
    })
  },
  onTabChange(e) {
    const {
      value
    } = e.detail;
    this.setData({
      status: value,
    });
    this.refreshList(value);
    console.log(value)
  },
  refreshList(status = -1) {
    this.page = {
      size: this.page.size,
      num: 1,
    };
    this.setData({
      curTab: status,
      orderList: []
    });

    return Promise.all([
      this.getOrderList(status, true),
      this.getOrdersCount(),
    ]);
  },
  showDialog(e) {
    const {
      cancel
    } = e.currentTarget.dataset;
    this.setData({
      showConfirm: true,
      dialogKey: cancel
    });
  },
  changOrderStatus(e) {
    const item = e.currentTarget.dataset.item;
    const cancel = e.currentTarget.dataset.cancel;
    if (item.order_status == 1) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: `宝贝正在打包中，请耐心等待哦~`,
        theme: 'success',
      });
    } else if (item.order_status == 3) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: `订单已完成，快分享给好友吧！`,
        theme: 'success',
      });
    } else if (item.order_status == 4) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: `再看看别的吧`,
        theme: 'success',
      });
    } else {
      if (item.order_status == 2) {
        this.setData({
          cntOrder: {
            order_no: item.order_no,
            order_status: 3
          }
        })
      } else if (item.order_status == 5) {
        if (cancel) {
          this.setData({
            cntOrder: {
              order_no: item.order_no,
              order_status: 4
            }
          })
        } else {
          this.setData({
            cntOrder: {
              order_no: item.order_no,
              order_status: 1
            }
          })
        }
      }
      this.showDialog(e)
    }

  },
  getOrdersCount() {

  },
  formatTime(date) {
    return formatTime(new Date(date), 'YYYY-MM-DD')
  },
  onRefresh() {
    this.refreshList(this.data.curTab);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getOrderList()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.reLaunch({
      url: '/pages/me/index'
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})